package com.qiaofang.applet.service.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.constants.MemberOperateTypeConstants;
import com.qiaofang.applet.service.member.domain.Member;
import com.qiaofang.applet.service.member.domain.MemberOperate;
import com.qiaofang.applet.service.member.repository.MemberOperateRepository;
import com.qiaofang.applet.service.member.repository.MemberRepository;
import com.qiaofang.applet.service.member.service.MemberShareService;
import com.qiaofang.applet.service.member.service.dto.MemberShareAddDto;
import com.qiaofang.applet.service.member.service.dto.MemberShareGetDto;
import com.qiaofang.applet.service.member.service.mapstruct.MemberOperateMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * @author Zym
 */
@Slf4j
@Service
public class MemberShareServiceImpl implements MemberShareService {

    @Autowired
    private MemberOperateRepository memberOperateRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MemberOperateMapper memberOperateMapper;

    @Autowired
    private MemberRepository memberRepository;

    /**
     * 添加一条分享记录
     * @param memberShareAddDto
     * @return
     */
    @Override
    public String addShareRecord(MemberShareAddDto memberShareAddDto) {
        log.info("add share params:{}", JSONObject.toJSONString(memberShareAddDto));
        MemberOperate memberOperate = memberOperateMapper.shareDtoToDomain(memberShareAddDto);
        log.info("share params Conver to memberOperate :{}", JSONObject.toJSONString(memberOperate));
        if (memberOperate.getBusinessType() != 4){
            Member member = memberRepository.findById(memberOperate.getMemberId()).get();
            if (member != null && member.getMemberType() == 2 && StringUtils.isNotEmpty(member.getEmployeeUniqueUuid())
                    && !memberOperate.getEmployeeUniqueUuid().equals(member.getEmployeeUniqueUuid())){
                memberOperate.setParentId(null);
                memberOperate.setShowEmpList(false);
                memberOperate.setEmployeeUniqueUuid(member.getEmployeeUniqueUuid());
            }
        }
        if (StringUtils.isEmpty(memberOperate.getParentId())){
            memberOperate.setLinkedUuid(getLinkedUuid());
            memberOperate.setLevel(0);
        }else {
            MemberOperate parentNode = memberOperateRepository.findFirstById(memberOperate.getParentId());
            String linkedUuid = parentNode.getLinkedUuid();
            //判断当前会员在该链路里是否有分享记录
            MemberOperate memberOperate1 = memberOperateRepository.findByMemberIdAndLinkedUuidAndOperateType(memberOperate.getMemberId(), linkedUuid, MemberOperateTypeConstants.SHARE.getValue());
            if (memberOperate1 != null){
                return memberOperate1.getId();
            }
            memberOperate.setLevel(parentNode.getLevel() + 1);
            memberOperate.setLinkedUuid(linkedUuid);
        }
        memberOperate.setOperateType(MemberOperateTypeConstants.SHARE.getValue());
        memberOperate.setCreateTime(new Date());
        memberOperate.setCorporationCode(QfContextHolder.getContext().getCorporationCode());
        log.info("insert share data to db:{}", JSONObject.toJSONString(memberOperate));
        return memberOperateRepository.insert(memberOperate).getId();
    }

    /**
     * 获取分享节点信息
     * @param id
     * @return
     */
    @Override
    public MemberShareGetDto getShareNodeInfo(String id) {
        MemberOperate memberOperate = memberOperateRepository.findFirstById(id);
        if (memberOperate == null){
            return new MemberShareGetDto();
        }
        return memberOperateMapper.domainToShareGetDto(memberOperate);
    }

    private String getLinkedUuid(){
        String linkedUuid = UUID.randomUUID().toString().replace("-", "").substring(0, 24);
        long count = mongoTemplate.count(new Query(Criteria.where("linkedUuid").is(linkedUuid)), MemberOperate.class);
        if (count > 0){
            return getLinkedUuid();
        }
        return linkedUuid;
    }
}
